<?

	session_start();
	if (empty($_SESSION[user]) && basename($_SERVER['PHP_SELF']) != "login.php")
	{
		header("Location:index.php");
	}


	$conn = mysqli_connect($config[dbhost], $config[dbuser], $config[dbpass], $config[dbname]);
	$con = new mysqli($config[dbhost], $config[dbuser], $config[dbpass], $config[dbname]);


	if (mysqli_connect_errno())
		die("Failed to connect to MySQL");


	function niceMail($to, $subject, $message)
	{
		$message = wordwrap($message, 70);
		global $config;
		$headers = "From: $config[systemtitle] <$config[hrEmail]>\r\n";
		mail($to, $subject, $message, $headers);
	}


	function daysUsed($yp, $u) //Counts up how many days the user in user has used in the specified year period
	{
		global $conn;
		$totalDaysUsed = 0;
		$duResult = mysqli_query($conn, "SELECT * FROM requests WHERE (user='$u' OR user='') AND (status='Pending' OR status='Accepted') AND yearperiod='$yp'");
		while ($du = mysqli_fetch_array($duResult))
			$totalDaysUsed += $du[days];
		return $totalDaysUsed;
	}
	


	function getEntitlement($yp) // Gets total number of days available in given year for current user
	{
		global $conn;
		$result = mysqli_query($conn, "SELECT entitlement, carriedover FROM users WHERE user='$_SESSION[user]' AND prestaged=0");
		$d = mysqli_fetch_array($result);
		
		if ($yp == date("Y"))
			return $d[entitlement] + $d[carriedover];
		else
			return $d[entitlement];

	}



	function getManager() // Gets username of manager for an employee
	{
		global $conn;
		$result = mysqli_query($conn, "SELECT manager FROM users WHERE user='$_SESSION[user]' AND prestaged=0");
		$d = mysqli_fetch_array($result);
		return $d[manager];
	}


	function getManagerEmail($u) // Gets email of manager for an employee
	{
		global $conn;
		$result = mysqli_query($conn, "SELECT email from users WHERE user in (SELECT manager FROM users WHERE user='$u' AND prestaged=0 AND deleted=0) AND prestaged=0 AND deleted=0");
		$d = mysqli_fetch_array($result);
		return $d[email];
	}


	function getOldWaitingApprovalsCount($old) // Find how many approvals are waiting for the current user for more than x days
	{
		global $conn;
		$result = mysqli_query($conn, "SELECT count(requests.requestid) AS totReq FROM users, requests WHERE (users.user = requests.user) AND users.manager='$_SESSION[user]' AND requests.status='Pending' AND requests.statusdate <= CURDATE()-$old");
		if (mysqli_num_rows($result) > 0)
		{
			$r = mysqli_fetch_array($result);
			return $r[totReq];
		}
		else
			return 0;
	}

	function getWaitingApprovalsCount() // Find how many approvals are waiting for the current user
	{
		global $conn;
		$result = mysqli_query($conn, "SELECT count(requests.requestid) AS totReq FROM users, requests WHERE (users.user = requests.user) AND users.manager='$_SESSION[user]' AND requests.status='Pending'");
		if (mysqli_num_rows($result) > 0)
		{
			$r = mysqli_fetch_array($result);
			return $r[totReq];
		}
		else
			return 0;
	}


	function getprestagedCount() // Find how many prestaged accounts are waiting
	{
		global $conn;
		$result = mysqli_query($conn, "SELECT count(*) AS totReq FROM users WHERE prestaged=1 AND deleted=0");
		if (mysqli_num_rows($result) > 0)
		{
			$r = mysqli_fetch_array($result);
			return $r[totReq];
		}
		else
			return 0;
	}


	function daysCalculation($sd, $ed, $st, $et) // Calculates how many days in a verios are holiday days - removes weekends and bank holidays
	{
		global $conn;
		$g = 0;
		$dtstart = new DateTime($sd);
		$dtend = new DateTime($ed);
		$oneday = new DateInterval("P1D");
		
		// Construct list of bank hols
		$bhol = array();
		$result = mysqli_query($conn, "SELECT date FROM bankhols WHERE date >= '$sd' AND date <= '$ed'");
		while ($b = mysqli_fetch_array($result))
			array_push($bhol, $b[date]);

		foreach(new DatePeriod($dtstart, $oneday, $dtend->add($oneday)) as $day)
		{
			$day_num = $day->format("N"); /* 'N' number days 1 (mon) to 7 (sun) */
			if($day_num < 6) { /* weekday */
				foreach ($bhol as $b)
				{
					if ($b == $day->format("Y-m-d"))
						$mandatory = true;
				}
				if (!$mandatory)
					$g++;
				$mandatory = FALSE;
			}
		}

		// Half days
		if ($st=="pm") { $g = $g-0.5; }
		if ($et=="am") { $g = $g-0.5; }
		if ($g<0) { $g = 0; } //Prevent people booking weekend holiday half days and getting a -0.5 added to holiday total!
		return $g;
	}




	function draw_calendar($month,$year) // Draws calendar!
	{

		$calendar = '<table cellpadding="0" cellspacing="0" class="calendar">';
		$headings = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
		$calendar.= '<tr class="calendar-row"><td class="calendar-day-head">'.implode('</td><td class="calendar-day-head">',$headings).'</td></tr>';
		$running_day = date('w',mktime(0,0,0,$month,1,$year));
		$days_in_month = date('t',mktime(0,0,0,$month,1,$year));
		$days_in_this_week = 1;
		$day_counter = 0;
		$dates_array = array();
		$calendar.= '<tr class="calendar-row">';
	
		// print "blank" days until the first of the current week
		for($x = 0; $x < $running_day; $x++):
			$calendar.= '<td class="calendar-day-np">&nbsp;</td>';
			$days_in_this_week++;
		endfor;

		for($list_day = 1; $list_day <= $days_in_month; $list_day++):
			$calendar.= '<td class="calendar-day">';
				$calendar.= '<div class="day-number">'.$list_day.'</div>';
	
				/** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !! **/

				global $conn;
				$today = "$year-$month-$list_day";
				
				// Get requests
				$result = mysqli_query($conn, "SELECT user, status FROM requests WHERE startdate <= '$today' AND enddate >= '$today' AND (status='Pending' OR status='Accepted') ORDER BY user");
				if (mysqli_num_rows($result) > 0)
				{
					while($r = mysqli_fetch_array($result))
					{
						// Colour clash username to show pending or accepted
						if ($r[status] == "Pending")
						{
							$sCol = "Blue";
							$sText = "(Pending)";
						}
						else
						{
							$sCol = "Green";
							$sText = "";
						}

						if ($r[user]=='')
							$u1 = "Compulsory";
						else
							$u1 = $r[user];
							
						$calendar .= "<div style='color:$sCol;background:white;border:1px solid;margin-bottom:1px;font-size:9px;line-height:12px'>$u1 $sText</div>";
					}
				}
				
				// Get bank hols
				$result = mysqli_query($conn, "SELECT date, name FROM bankhols WHERE date = '$today'");
				if (mysqli_num_rows($result) > 0)
				{
					while($r = mysqli_fetch_array($result))
						$calendar .= "<div style='color:red;background:white;border:1px solid;margin-bottom:1px;font-size:9px;line-height:12px'>$r[name]</div>";
				}



				//$calendar.= str_repeat('<p>&nbsp;</p>',2);
			
			$calendar.= '</td>';
			if($running_day == 6):
				$calendar.= '</tr>';
				if(($day_counter+1) != $days_in_month):
					$calendar.= '<tr class="calendar-row">';
				endif;
				$running_day = -1;
				$days_in_this_week = 0;
			endif;
			$days_in_this_week++; $running_day++; $day_counter++;
		endfor;

		if($days_in_this_week < 8):
			for($x = 1; $x <= (8 - $days_in_this_week); $x++):
				$calendar.= '<td class="calendar-day-np">&nbsp;</td>';
			endfor;
		endif;

		$calendar.= '</tr>';
		$calendar.= '</table>';
	
		return $calendar;
}


function sendCalendar($email, $title, $start, $end, $user)
{


// DEBUGONLY $start = "20130215T121000Z";
// DEBUGONLY $end = "20130215T131000Z";
$now = date("Ymd") . "T" . date("His") . "Z";

if ($user != "")
{
  if ($title == "")
    $title = $user;
  else
    $title = $user . " - " . $title;
}

if ($user == "")
{
  $transp = "OPAQUE"; // User
  $busyst = "OOF";
}
else
{
  $transp = "TRANSPARENT"; // Manager
  $busyst = "FREE";
}

$message="BEGIN:VCALENDAR
VERSION:2.0
CALSCALE:GREGORIAN
METHOD:REQUEST
BEGIN:VEVENT
DTSTART:$start
DTEND:$end
DTSTAMP:$now
ORGANIZER;CN=$config[systemtitle]:mailto:$config[hrEmail]
UID:$now
ATTENDEE;PARTSTAT=NEEDS-ACTION;RSVP=FALSE;CN=Sample:mailto:$email
DESCRIPTION:Generated via $config[systemtitle] - $config[url]
LOCATION:
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY:Holiday - $title
TRANSP:$transp
X-MICROSOFT-CDO-BUSYSTATUS:$busyst
END:VEVENT
END:VCALENDAR";

/*Setting the header part, this is important */
$headers = "From: $config[systemtitle] <$config[hrEmail]>\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: text/calendar; method=REQUEST;\n";
$headers .= '        charset="UTF-8"';
$headers .= "\n";
$headers .= "Content-Transfer-Encoding: 7bit";

/*mail content , attaching the ics detail in the mail as content*/
$subject = html_entity_decode($subject, ENT_QUOTES, 'UTF-8');

/*mail send*/
mail($email, "Holiday - " . $title, $message, $headers);

}



?>
